package cn.leizp.springboot.auth.frontweb.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;

public class JsonAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        System.out.println("==开始处理登录验证==");
        if ("application/json".equals(request.getContentType())) {
            try (BufferedReader reader = request.getReader()) {
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                Map<String, String> loginData = objectMapper.readValue(sb.toString(), Map.class);
                String username = loginData.get("username");
                String password = loginData.get("password");
                System.out.println("==" + username + "==" + password + "==");
                UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username,
                        password);
                setDetails(request, authRequest);
                Authentication authentication = this.getAuthenticationManager().authenticate(authRequest);
                System.out.println("==登录验证成功完成==");
                return authentication;
            } catch (IOException e) {
                System.out.println("==请求解析失败==");
                // 处理 IO 异常
                handleAuthenticationFailure(response, "请求解析失败", HttpServletResponse.SC_BAD_REQUEST);
            } catch (AuthenticationException e) {
                System.out.println("==用户名或密码错误==");
                // 处理认证异常
                handleAuthenticationFailure(response, "用户名或密码错误", HttpServletResponse.SC_UNAUTHORIZED);
            } catch (Exception e) {
                System.out.println("==系统错误，请稍后重试==");
                // 处理其他异常
                handleAuthenticationFailure(response, "系统错误，请稍后重试", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
            return null;
        } else {
            return super.attemptAuthentication(request, response);
        }
    }

    private void handleAuthenticationFailure(HttpServletResponse response, String message, int statusCode) {
        try {
            response.setStatus(statusCode);
            response.setContentType("application/json;charset=UTF-8");
            // 构建错误响应 JSON
            String errorJson = objectMapper.writeValueAsString(Map.of("message", message));
            response.getWriter().write(errorJson);
        } catch (IOException e) {
            System.err.println("写入错误响应失败: " + e.getMessage());
        }
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
            jakarta.servlet.FilterChain chain, Authentication authResult)
            throws IOException, jakarta.servlet.ServletException {
        //System.out.println("==准备启动验证成功处理逻辑==");
        // 调用配置的 AuthenticationSuccessHandler
	    AuthenticationSuccessHandler successHandler = getSuccessHandler();
	    //System.out.println("获取到的 AuthenticationSuccessHandler 类名: " + successHandler.getClass().getName());
	    successHandler.onAuthenticationSuccess(request, response, authResult);
    }
}
